"use client";

import React, { useState, useEffect } from "react";
import Link from "next/link";
import { Layout, Button, Card, List, Pagination, Menu, Badge } from "antd";
import {
  LikeOutlined,
  CommentOutlined,
  StarOutlined,
  PlusOutlined,
} from "@ant-design/icons";
import api from "../../utils/api";
import fontStyles from "@/components/Font.module.css"; // 引入字体样式
import postCardStyles from "@/components/PostCard.module.css";
import buttonStyles from "@/components/Buttons.module.css"; // 引入按钮样式

const { Sider, Content } = Layout;

export default function HomePage() {
  const [posts, setPosts] = useState([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(4);
  const [currentCategory, setCurrentCategory] = useState("all");
  const [categories, setCategories] = useState([]);
  const [loading, setLoading] = useState(true);
  const [hotPosts, setHotPosts] = useState([]);

  useEffect(() => {
    fetchCategories();
    fetchPosts();
    fetchHotPosts();
  }, [page, currentCategory]);

  const fetchCategories = async () => {
    try {
      const response = await api.get("/categories/all");
      console.log("分区数据响应:", response.data);
      if (response.status === 200 && Array.isArray(response.data.Reponse)) {
        setCategories(response.data.Reponse);
      } else {
        setCategories([]);
      }
    } catch (error) {
      console.error("获取分区数据失败:", error);
      setCategories([]);
    } finally {
      setLoading(false);
    }
  };

  const fetchPosts = async () => {
    try {
      let url = "/posts/list";
      let params = {
        page: String(page),
        pageSize: String(pageSize),
      };

      if (currentCategory !== "all") {
        url = "/posts/category";
        params = {
          ...params,
          categoryId: String(currentCategory),
        };
      }

      console.log("请求 URL:", url);
      console.log("请求参数:", params);

      const response = await api.get(url, { params });

      if (response.status === 200) {
        const postsData = Array.isArray(response.data.posts)
          ? response.data.posts
          : [];
        const totalCount = response.data.total || 0;

        const postsWithDisplayName = await Promise.all(
          postsData.map(async (post) => {
            try {
              const userResponse = await api.get("/users/info", {
                params: { id: post.authorId },
              });
              const pinnedStatus = post.Pinned || false;
              return {
                ...post,
                authorDisplayName:
                  userResponse.data?.display_name || "未知作者",
                isPinned: pinnedStatus,
              };
            } catch (error) {
              console.error(`获取作者 ${post.authorId} 信息失败:`, error);
              return {
                ...post,
                authorDisplayName: "未知作者",
                isPinned: false,
              };
            }
          })
        );

        setPosts(postsWithDisplayName);
        setTotal(totalCount);
      }
    } catch (error) {
      console.error("获取帖子列表失败:", error);
      setPosts([]);
      setTotal(0);
    }
  };

  const fetchHotPosts = async () => {
    try {
      const response = await api.get("/posts/listHot", {
        params: { pageSize: 10 },
      });
      if (response.status === 200) {
        setHotPosts(response.data.posts || []);
      }
    } catch (error) {
      console.error("获取热帖数据失败:", error);
      setHotPosts([]);
    }
  };

  const handlePageChange = (newPage) => {
    setPage(newPage);
  };

  const handleCategoryChange = (key) => {
    setCurrentCategory(key);
    setPage(1);
  };

  return (
    <Layout style={{ display: "flex", backgroundColor: "transparent" }}>
      {/* Category 分区 */}
      <Menu
        mode="horizontal"
        selectedKeys={[currentCategory]}
        style={{
          marginTop: 20,
          marginBottom: 10,
          width: "68.5%",
          position: "fixed",
          top: "64px",
          zIndex: 1,
          backgroundColor: " #F0E6E2",
          borderRadius: "12px", // 圆角边框
          height: "50px", // 高度适配
        }}
        selectable
        onSelect={({ key }) => handleCategoryChange(key)}
      >
        <Menu.Item
          disabled // 鼠标不可点击
          style={{
            fontSize: "20px",
            fontWeight: 600,
            marginLeft: "20px",
          }}
        >
          分区
        </Menu.Item>
        <Menu.Item key="all" onClick={() => handleCategoryChange("all")}>
          全部
        </Menu.Item>
        {!loading &&
          categories.map((category) => (
            <Menu.Item
              key={category.id}
              className={fontStyles.menuItem} // 使用自定义字体样式
              onClick={() => handleCategoryChange(category.id)}
            >
              {category.name}
            </Menu.Item>
          ))}
      </Menu>

      {/* 帖子列表 */}
      <Layout
        style={{
          paddingTop: "10px",
          height: "83vh",
          borderRadius: "16px", // 圆角边框
          backgroundColor: "rgba(255, 255, 255, 0.5)", // 半透明白色背景
          overflow: "hidden", // 如果子内容有圆角边缘，建议加这一句
        }}
      >
        {/* 主内容区 */}
        <Content
          style={{
            height: "80vh", // Header是64px的情况
            overflowY: "auto",
            padding: "20px",
          }}
        >
          <List
            itemLayout="vertical"
            dataSource={posts}
            renderItem={(item) => (
              <Link href={`/posts/${item.id}`} passHref prefetch>
                <Card
                  hoverable
                  style={{
                    width: "98%",
                    margin: "0 auto 14px",
                    cursor: "pointer",
                    borderRadius: "16px",
                  }}
                >
                  <Card.Meta
                    title={
                      <div
                        className={postCardStyles.cardMetaTitle}
                        style={{ fontSize: "20px", fontWeight: "bold" }}
                      >
                        {item.isPinned && currentCategory !== "all" && (
                          <Badge
                            status="processing"
                            text="置顶"
                            style={{
                              marginRight: 8,
                              backgroundColor: "#FFA500",
                              color: "white",
                              borderRadius: 4,
                              padding: "2px 6px",
                            }}
                          />
                        )}
                        {item.title}
                      </div>
                    }
                    description={
                      <div className={postCardStyles.cardAuthor}>
                        作者：{item.authorDisplayName}
                      </div>
                    }
                  />
                  <div className={postCardStyles.cardContent}>
                    {item.content}
                  </div>
                  <div className={postCardStyles.cardActions}>
                    <Button
                      type="text"
                      icon={<LikeOutlined />}
                      className={postCardStyles.cardButton}
                    >
                      {item.likes}
                    </Button>
                    <Button
                      type="text"
                      icon={<CommentOutlined />}
                      className={postCardStyles.cardButton}
                    >
                      {item.comments}
                    </Button>
                    <Button
                      type="text"
                      icon={<StarOutlined />}
                      className={postCardStyles.cardButton}
                    >
                      {item.favourites}
                    </Button>
                  </div>
                </Card>
              </Link>
            )}
          />

          <div style={{ display: "flex", justifyContent: "center" }}>
            <Pagination
              current={page}
              pageSize={pageSize}
              total={total}
              onChange={handlePageChange}
            />
          </div>
        </Content>
      </Layout>

      {/* 侧边栏 */}
      <Sider
        width="28%"
        style={{
          background: "transparent",
          marginTop: "-32px",
          padding: "5px",
          paddingLeft: "25px",
        }}
      >
        {/* 发帖按键 */}
        <Link href="/posts/createPost">
          <Button
            type="default"
            icon={<PlusOutlined />}
            block
            className={buttonStyles.Button1}
            style={{
              fontSize: "22px",
              padding: "10px 16px",
              height: "64px",
              fontWeight: "bold",
            }}
          >
            发布帖子
          </Button>
        </Link>
        {/* 热门帖子——标题*/}
        <h3
          style={{
            fontSize: "18px",
            fontWeight: "bold",
            marginTop: "40px",
            marginBottom: "20px",
            color: "#594a4e",
            textAlign: "left", // 左对齐
          }}
        >
          帖子热度排行榜
        </h3>
        {/* 热门帖子——列表*/}
        <List
          itemLayout="vertical"
          dataSource={hotPosts}
          renderItem={(item) => (
            <List.Item
              style={{ padding: "5px 0", borderBottom: "1px solid #e8e8e8" }}
            >
              {/* 帖子标题 */}
              {/* 标题样式 */}
              <style jsx>{`
                .post-link {
                  color: #594a4e;
                  font-weight: 500;
                  font-size: 16px;
                  display: block;
                  margin-bottom: 2px;
                  text-decoration: none;
                  transition: all 0.2s ease;
                }
                .post-link:hover {
                  color: #aaa; /* 鼠标悬停时的颜色 */
                  cursor: pointer;
                }
              `}</style>
              {/* 帖子链接 */}
              <Link href={`/posts/${item.id}`} passHref prefetch>
                <span className="post-link">{item.title}</span>
              </Link>
              {/* 帖子信息 */}
              <span style={{ color: "#888", fontSize: 11, textAlign: "right" }}>
                浏览量: {item.views} | 点赞数: {item.likes} | 收藏数:{" "}
                {item.favourites}
              </span>
            </List.Item>
          )}
        />
      </Sider>
    </Layout>
  );
}
